//
//  AppDelegate.m
//  met
//
//  Created by 李晓俊 on 2019/4/28.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "AppDelegate.h"
#import "UIViewController+Swizzled.h"
#import "MainTabBarController.h"
#import "CYLMainRootViewController.h"

#import "MTLoginHomeVC.h"

#import "MTShouQuanVC.h"

#import <UMCommon/UMCommon.h>           // 公共组件是所有友盟产品的基础组件，必选
#import <UMShare/UMShare.h>
#import <CoreLocation/CoreLocation.h>

#import "ZLAdvertView.h"
@interface AppDelegate ()<CLLocationManagerDelegate>

@end

@implementation AppDelegate{
    CLLocationManager * _locationManager;       // 位置管理器
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
#ifdef DEBUG
    [UIViewController swizzIt];
#else
#endif
//    for (NSString *fontfamilyname in [UIFont familyNames])
//    {
//        DLog(@"family:'%@'",fontfamilyname);
//        for(NSString *fontName in [UIFont fontNamesForFamilyName:fontfamilyname])
//        {
//            DLog(@"\tfont:'%@'",fontName);
//        }
//        DLog(@"-------------");
//    }
    
    // U-Share 平台设置
    [self configUSharePlatforms];
    [self confitUShareSettings];
//    [MobClick setScenarioType:E_UM_NORMAL];
    //
    
    
    self.window = [[UIWindow alloc]init];
    self.window.frame = [UIScreen mainScreen].bounds;
    [self.window makeKeyAndVisible];

    [self.window setRootViewController:[UIViewController new]];

    [self setupAdvert];

    

//
//    NSDictionary *dic = [UserDefaultStandard objectForKey:@"userinfo"];
//    if (dic) {
//        KUSER = [UserInfo mj_objectWithKeyValues:dic];
//    }else {
//        KUSER = [UserInfo mj_objectWithKeyValues:[NSDictionary new]];
//    }
//    if ( [[NSString stringWithFormat:@"%@",KUSER.nickName] length] > 0) {
//        MTShouQuanVC *vc = GetViewControllerInStoryboard(@"Login", @"MTShouQuanVC");
//        BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:vc];
//        [self.window setRootViewController:nav];
//    }else {
//        BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:GetViewControllerInStoryboard(@"Login", @"MTLoginHomeVC")];
//        [self.window setRootViewController:nav];
//    }
    
    [self setNavBarAppearence];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;

    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    EMOptions *options = [EMOptions optionsWithAppkey:HuanXinAppKey];
    //    options.apnsCertName = @"istore_dev";
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    [[EaseSDKHelper shareHelper] hyphenateApplication:application
                        didFinishLaunchingWithOptions:launchOptions
                                               appkey:HuanXinAppKey
                                         apnsCertName:nil
                                          otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
    //创建数据库
    [[DataBaseManager sharedInstance] createDataBase];
    
    if (_locationManager == nil) {
        _locationManager = [CLLocationManager new];
    }
    _locationManager.delegate = self;
    
    
    
    //注册token
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//        //可以添加自定义categories
//        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
//                                                          UIUserNotificationTypeSound |
//                                                          UIUserNotificationTypeAlert)
//                                              categories:nil];
//    } else {
//        //categories 必须为nil
//        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
//                                                          UIRemoteNotificationTypeSound |
//                                                          UIRemoteNotificationTypeAlert)
//                                              categories:nil];
//    }
//
//
//    [JPUSHService setupWithOption:launchOptions appKey:@"b23bccf40e4477f7168e32d5"
//                          channel:@"developer-default" apsForProduction:YES];
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

    
    
    
    return YES;
}

-(void)application:(UIApplication* )application didRegisterForRemoteNotificationsWithDeviceToken:(NSData* )deviceToken{
    //获取deviceToken
    NSLog(@"%@",deviceToken);
    NSString *token = [deviceToken description];
    NSString *pushToken = [[[token  stringByReplacingOccurrencesOfString:@"<" withString:@""]                   stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    [JPUSHService registerDeviceToken:deviceToken];
    
}

- (void)confitUShareSettings
{
    //     打开图片水印
    [UMConfigure initWithAppkey:UMShareid channel:@"App Store"];
    [UMSocialGlobal shareInstance].isUsingWaterMark = NO;
    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}
- (void)configUSharePlatforms
{
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WXAppid appSecret:WXAppKey redirectURL:nil];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatFavorite appKey:WXAppid appSecret:WXAppKey redirectURL:nil];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:WXAppid appSecret:WXAppKey redirectURL:nil];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[EMClient sharedClient] applicationDidEnterBackground:application];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[EMClient sharedClient] applicationWillEnterForeground:application];
//    if ([[NSString stringWithFormat:@"%@",KUSER.nickName]length] > 0) {
//        [self location];
//    }
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [JPUSHService setBadge:0];
    [JPUSHService resetBadge];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)setNavBarAppearence
{
    // 设置是 广泛使用WRNavigationBar，还是局部使用WRNavigationBar，目前默认是广泛使用
    [WRNavigationBar wr_widely];
    [WRNavigationBar wr_setBlacklist:@[@"SpecialController",
                                       @"TZPhotoPickerController",
                                       @"TZGifPhotoPreviewController",
                                       @"TZAlbumPickerController",
                                       @"TZPhotoPreviewController",
                                       @"TZVideoPlayerController"]];
    
    // 设置导航栏默认的背景颜色
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:KMainColor];
    // 设置导航栏所有按钮的默认颜色
    [WRNavigationBar wr_setDefaultNavBarTitleColor:KBlackColor];
     // 统一设置状态栏样式
//    [WRNavigationBar wr_setDefaultStatusBarStyle:UIStatusBarStyleDefault];
    // 如果需要设置导航栏底部分割线隐藏，可以在这里统一设置
//    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
}



- (void)location {
    if ([CLLocationManager locationServicesEnabled]) {
        // 判断用户是否允许程序获取位置权限
        if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedAlways) {
 
        }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse) {
            //部分权限
            self.window = [[UIWindow alloc]init];
            self.window.frame = [UIScreen mainScreen].bounds;
            [self.window makeKeyAndVisible];
            MTShouQuanVC *vc = GetViewControllerInStoryboard(@"Login", @"MTShouQuanVC");
            BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:vc];
            [self.window setRootViewController:nav];
        } else {
            //用户还未开启用户权限
            self.window = [[UIWindow alloc]init];
            self.window.frame = [UIScreen mainScreen].bounds;
            [self.window makeKeyAndVisible];
            MTShouQuanVC *vc = GetViewControllerInStoryboard(@"Login", @"MTShouQuanVC");
            BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:vc];
            [self.window setRootViewController:nav];
        }
    }else {
        //用户拒绝开启用户权限
        self.window = [[UIWindow alloc]init];
        self.window.frame = [UIScreen mainScreen].bounds;
        [self.window makeKeyAndVisible];
        MTShouQuanVC *vc = GetViewControllerInStoryboard(@"Login", @"MTShouQuanVC");
        BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:vc];
        [self.window setRootViewController:nav];
    }
}
/** 定位服务状态改变时调用*/
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if ([[NSString stringWithFormat:@"%@",KUSER.nickName]length] > 0) {
        if (status == kCLAuthorizationStatusAuthorizedAlways ) {
            DLog(@"获得所有授权");
            [self setupAdvert];
//            self.window = [[UIWindow alloc]init];
//            self.window.frame = [UIScreen mainScreen].bounds;

//            MTShouQuanVC *vc = GetViewControllerInStoryboard(@"Login", @"MTShouQuanVC");
//            BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:vc];
//            [self.window setRootViewController:nav];
//            [self.window makeKeyAndVisible];

        }else {
            [self setupAdvert];
//            self.window = [[UIWindow alloc]init];
//            self.window.frame = [UIScreen mainScreen].bounds;
//            [self.window makeKeyAndVisible];
//            MTShouQuanVC *vc = GetViewControllerInStoryboard(@"Login", @"MTShouQuanVC");
//            BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:vc];
//            [self.window setRootViewController:nav];
        }
    }
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    
    if(application.applicationState == UIApplicationStateActive)
    {
        //前台收到推送
//        [self alert:@"通知" msg:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]];
    }
    else
    {
        
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alter show];
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}



- (void)pushvc {
    NSDictionary *dic = [UserDefaultStandard objectForKey:@"userinfo"];
    if (dic) {
        KUSER = [UserInfo mj_objectWithKeyValues:dic];
    }else {
        KUSER = [UserInfo mj_objectWithKeyValues:[NSDictionary new]];
    }
    if ( [[NSString stringWithFormat:@"%@",KUSER.nickName] length] > 0) {
        MTShouQuanVC *vc = GetViewControllerInStoryboard(@"Login", @"MTShouQuanVC");
        BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:vc];
        [self.window setRootViewController:nav];
    }else {
        BasicNavigationController *nav = [[BasicNavigationController alloc]initWithRootViewController:GetViewControllerInStoryboard(@"Login", @"MTLoginHomeVC")];
        [self.window setRootViewController:nav];
    }
}

/**
 *  设置启动页广告
 */
- (void)setupAdvert {
    // 1.判断沙盒中是否存在广告图片，如果存在，直接显示
    NSString *filePath = [self getFilePathWithImageName:[kUserDefaults valueForKey:adImageName]];
    
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (isExist) { // 图片存在
        ZLAdvertView *advertView = [[ZLAdvertView alloc] initWithFrame:CGRectMake(0, 0, kscreenWidth, kscreenHeight)
                                    ];
        //        self.window.bounds];
        advertView.filePath = filePath;
        advertView.doneCLick = ^(NSString *n) {
            [self pushvc];
        };
        [advertView show];
    }else {
        [self pushvc];
    }
    // 2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告是否更新
    [self getAdvertisingImage];
}

/**
 *  判断文件是否存在
 */
- (BOOL)isFileExistWithFilePath:(NSString *)filePath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}
/**
 *  初始化广告页面
 */
- (void)getAdvertisingImage {
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            NSArray *ar = [data objectForKey:@"data"];
            if (ar.count>0) {
                NSString *imageUrl = [ar objectAtIndex:0];
                // 获取图片名:43-130P5122Z60-50.jpg
                NSArray *stringArr = [imageUrl componentsSeparatedByString:@"/"];
                NSString *imageName = stringArr.lastObject;
                
                // 拼接沙盒路径
                NSString *filePath = [self getFilePathWithImageName:imageName];
                BOOL isExist = [self isFileExistWithFilePath:filePath];
                if (!isExist){ // 如果该图片不存在，则删除老图片，下载新图片
                    [self downloadAdImageWithUrl:imageUrl imageName:imageName];
                }
            }
        }else {
//            [self.view maketishiToast:data];
        }
    };
    [acc startPageFind];
    
    // TODO 请求广告接口
    // 这里原本应该采用广告接口，现在用一些固定的网络图片url代替
//        NSArray *imageArray = @[
//                                @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg",
//                                @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg",
//                                @"http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"
//                                ];
//        NSString *imageUrl = imageArray[arc4random() % imageArray.count];
//    // 获取图片名:43-130P5122Z60-50.jpg
//    NSArray *stringArr = [imageUrl componentsSeparatedByString:@"/"];
//    NSString *imageName = stringArr.lastObject;
//    
//    // 拼接沙盒路径
//    NSString *filePath = [self getFilePathWithImageName:imageName];
//    BOOL isExist = [self isFileExistWithFilePath:filePath];
//    if (!isExist){ // 如果该图片不存在，则删除老图片，下载新图片
//        [self downloadAdImageWithUrl:imageUrl imageName:imageName];
//    }
//    
}
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        NSString *filePath = [self getFilePathWithImageName:imageName]; // 保存文件的名称
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功
            NSLog(@"保存成功");
            [self deleteOldImage];
            [kUserDefaults setValue:imageName forKey:adImageName];
            [kUserDefaults synchronize];
            // 如果有广告链接，将广告链接也保存下来
        }else{
            DLog(@"保存失败");
        }
        
    });
}

/**
 *  删除旧图片
 */
- (void)deleteOldImage {
    
    NSString *imageName = [kUserDefaults valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

/**
 *  根据图片名拼接文件路径
 */
- (NSString *)getFilePathWithImageName:(NSString *)imageName {
    
    if (imageName) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    
    return nil;
}
@end
